<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>upload</title>
    <link type="text/css" rel="stylesheet" href="../css/bootstrap.css"/>
    <style type="text/css">
        .res-list {
            display: table;
            background-color: #f7f7f7;
            border: solid 1px #e5e5e5;
            padding: 16px;
            -webkit-border-radius: 16px;
            -moz-border-radius: 16px;
            border-radius: 16px;
        }

        .res-list .res {
            display: table-row;
            height: 64px;
            background-color: #d5d5d5;
            /*d6e9c6*/
        }

        .res-list .res .cell {
            display: table-cell;
            vertical-align: middle;
        }

        #add-btn {
            width: 64px;
            height: 64px;
            border: dashed 2px #b9def0;
            color: #2aabd2;
            background-color: #d9edf7;
            /*2aabd2*/
            margin-top: 16px;
            -webkit-border-radius: 8px;
            -moz-border-radius: 8px;
            border-radius: 8px;
        }

        #send-btn{
            float: right;
            background-color: #2aabd2;
            color: #ffffff;
            margin-top:16px;
        }
    </style>
</head>
<body>
<div class="container">
    <h3>file upload</h3>
    <input type="file" id="file" style="display: none;" multiple accept="image/*"
           onchange="selectFiles(this.files)"/>
    <div class="row">
        <div class="res-list col-lg-8">
            <button class="btn btn-default btn-lg" id="add-btn">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
            </button>
        </div>
    </div>
    <div class="row col-lg-8">
        <button type="button" onclick="sendFiles()" id="send-btn" class="btn btn-default btn-lg">Send</button>
    </div>
</div>
<script src="../js/jquery-3.2.1.min.js"></script>
<script src="../js/jquery.md5.js"></script>
<script>
    $(function () {
        $("#add-btn").click(function () {
            $("#file").click();
        });
    });

    var resourceLoader = function(file){

        this.file=file;
        var pointIndex = file.name.lastIndexOf('.');
        this.suffix = file.name.substr(pointIndex);
        this.name=file.name.substring(0, this.suffix);

        this.load = function(){
            console.log('suffix is:'+ this.suffix);
            return this.loadResource();
        }

        this.loadResource = function(){
            if(this.suffix=='.jpg'|| this.suffix==".jpeg" || this.suffix==".png"){
                return this.loadImgResource();
            }else{
                console.log("unknow handle 4 type:"+this.suffix);
            }
        }

        this.loadImgResource= function(){
            var img = document.createElement('img');
            img.src = window.URL.createObjectURL(this.file);
            img.name = this.name;
            img.filename = this.file.name;
            img.width = 64;
            img.height = 64;
            img.classList.add('obj');
            img.onload = function() {
                window.URL.revokeObjectURL(this.src);
            }

            var reader = new FileReader();
            reader.onload = function (event) {
                // md5 sign
                var md5Str = $.md5(event.target.result);
                img.file = event.target.result;
                img.md5Str = md5Str;
                console.log('hash code:' + md5Str);
            }
            reader.readAsBinaryString(this.file);

            return img;
        }
    }

    function selectFiles(files) {
//        show every file in the page
        for (var i = 0; i < files.length; i++) {
            var resRoot = $('<div class="res row"></div>');
            var echo = $('<div class="echo cell"></div>');
            var res = new resourceLoader(files[i]).load();
            console.log(res);
            echo.append($(res));
            var name = $('<div class="name cell">'+files[i].name+'</div>');
            var size = $('<div class="size cell">'+files[i].size+'bytes</div>');
            var btn = $('<button type="button" class="close" aria-label="Close" onclick="removeFromParent(this)">' +
                         '<span aria-hidden="true">&times;</span>' +
                      '</button>');
            resRoot.append(echo, name, size,btn);
            $("#add-btn").before(resRoot);
        }
    }

    function removeFromParent(e) {
        $(e).parent().remove();
    }

    function sendFiles(){
        var objs = document.querySelectorAll(".obj");
        for(var i=0; i<files.length;i++){
            var segments = [];
            var obj = objs[i];
            var file = obj.file;
            var name = obj.name;
            var filename = obj.filename;
            var md5 = obj.md5Str;
            var type = obj.type;
//            "Content-Disposition: form-data; name=\"" + oField.name + "\"\r\n\r\n" + oField.value + "\r\n"
//            "Content-Disposition: form-data; name=\"" +
//            oField.name + "\"; filename=\"" + oFile.name +
//            "\"\r\nContent-Type: " + oFile.type + "\r\n\r\n"
            segments.push("Content-Disposition: form-data; name=\"name\"\r\n\r\n"+name+"\r\n");
            segments.push("Content-Disposition: form-data; name=\"md5Str\"\r\n\r\n"+md5+"\r\n");
            segments.push("Content-Disposition: form-data; name=\"file\"; filename=\""+filename+"\"\r\nContent-Type: "
            +type+"\r\n\r\n"+file+"\r\n");
            send(segments);
        }
    }

    function send(segments){
        var req = new XMLHttpRequest();
        req.open("POST", "http://local:13800/file", true);
        req.addEventListener("progress", updateProgress);
        req.addEventListener("load", transferComplete);
        req.addEventListener("error", transferFailed);
        req.addEventListener("abort", transferCanceled);
        req.addEventListener("readystatechange", onsuccess(req.responseText));
        var boundary = '---------------------------'+Date().now().toString(16);
        req.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + boundary);
        req.sendAsBinary("--" + boundary + "\r\n" +
            segments.join("--" + boundary + "\r\n") + "--" + boundary + "--\r\n");
    }

    function updateProgress(event){
        console.log('evt onprogress:');
        console.log(event);
        if (oEvent.lengthComputable) {
            var percent = event.loaded / event.total;
            // ...
            console.log();
        }
    }

    function transferComplete(event){

    }

    function transferFailed(event){

    }

    function transferCanceled(event){

    }

    function onsuccess(responseText){
        if (xhr.readyState == 4 && xhr.status == 200){
            console.log('response text:');
            console.log(responseText); // handle response.
        }
    }

</script>
</body>
</html>









